﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web;
using System.Xml;

using Blazing.BusinessObjects;
using Blazing.BusinessObjects.Cms;
using Blazing.BusinessObjects.Queries;
using Blazing.WebFacade;
using Blazing.WebFacade.Extensions;
using Iesi.Collections;
using Iesi.Collections.Generic;

namespace Blazing.Web.Handlers
{
    class SitemapHandler : IHttpHandler
    {
        #region IHttpHandler Members

        public bool  IsReusable
        {
            get { return false; }
        }

        public void ProcessRequest(HttpContext context)
        {
            HttpResponse response = context.Response;
            PageController pctrl = new PageController();
            string hostUrl = context.Request.Url.Host;
            Site s = context.Request.Url.GetSite();
            string siteMapHost = (s.Url.StartsWith("http") ? "" : "http://") + s.Url;

            ISet<Contentpage> pages = pctrl.GetPages(s.ID);

            if (pages != null && pages.Count > 0)
            {
                using (XmlTextWriter writer = new XmlTextWriter(response.OutputStream, Encoding.UTF8))
                {
                    writer.Formatting = Formatting.Indented;
                    writer.WriteStartDocument();
                    writer.WriteStartElement("urlset", "http://www.sitemaps.org/schemas/sitemap/0.9");

                    foreach (Contentpage page in pages)
                    {
                        writer.WriteStartElement("url");
                        writer.WriteElementString("loc", siteMapHost + page.Url);
                        writer.WriteElementString("lastmod", page.RowStamp.ToUniversalTime().ToString("yyyy-MM-dd"));
                        writer.WriteEndElement();
                    }

                    writer.WriteEndElement(); // urlset
                    writer.WriteEndDocument();
                }
            }
            else
            {
                response.StatusCode = 404;
                response.StatusDescription = "404 Not Found";
            }
        }

        #endregion
    }
}